# coding:UTF-8

import logging

from django.shortcuts import render_to_response
from django.db.models import Q
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect

from home.models import BlogComment as BlogCommentDb
from controller.typechanging import NAME_TO_TYPE
from myblogs.models import BlogInfo as BlogInfoDb
from account.models import Message as MessageDb

logger = logging.getLogger(__name__)

def load_data(blog_list):
    return {
        'new_blog': blog_list.order_by('-createTime'),
        'hot_blog': blog_list.order_by('-scan_count'),
        'classical_blog': blog_list.order_by('-praise_count')
    }


def home(request):
    if request.method == "GET":
        article_type = request.GET.get('type', None)
        if article_type == "all" or not article_type:
            logger.info("One Person Come Here!")
            return get_all_article(request)
        else:
            chinese_type = NAME_TO_TYPE.get(article_type, '')
            return get_article_by_type(request, chinese_type)


def get_all_article(request):
    blog_list = BlogInfoDb.objects.filter(status="True")
    obj = load_data(blog_list)
    obj['title'] = '首页'
    if request.session.get('status') == 'login':
        obj['login'] = True
        obj['session'] = request.session

    return render_to_response(
        "home/index.html",
        {
            'obj': obj
        },
        context_instance=RequestContext(request)
    )


def get_article_by_type(request, chinese_type):
    # 传入的chinese是GBK编码中文字符，不过mac是assic，首先转化成unicode编码再转化成UTF-8编码
    # 因为数据库是UTF-8编码
    chinese_type = chinese_type.encode("UTF-8")
    blog_list = BlogInfoDb.objects.filter(blog_tags=chinese_type, status="True")
    obj = load_data(blog_list)
    obj['title'] = chinese_type
    if request.session.get('status') == 'login':
        obj['login'] = True
        obj['session'] = request.session

    return render_to_response(
        "home/index.html",
        {
            'obj': obj
        },
        context_instance=RequestContext(request)
    )


def find_blog_by_id(request, blog_id):
    obj = {}
    if request.method == "GET":
        try:
            blog = BlogInfoDb.objects.get(id=blog_id)
            blog.scan_count += 1
            blog.save()
            obj['blog'] = blog
            comment_list = BlogCommentDb.objects.filter(blog_id=blog_id).order_by('createTime')

            if request.session.get('status') == 'login':
                obj['login'] = True
                obj['session'] = request.session
            else:
                if request.META.has_key('HTTP_X_FORWARDED_FOR'):
                    ip_detail = request.META['HTTP_X_FORWARDED_FOR'] + " " + request.META['HTTP_USER_AGENT']
                else:
                    ip_detail = request.META['REMOTE_ADDR'] + " " + request.META['HTTP_USER_AGENT']
                # Redis Test
                # from controller.settings import read_from_cache, write_to_cache
                # try:
                #     online_user_list = read_from_cache("online_user_list")
                # except Exception:
                #     online_user_list = []
                # else:
                #     import json
                #     online_user_list = json.loads(online_user_list)
                #     online_user_list.append(ip_detail)
                # print online_user_list
                # write_to_cache("online_user_list", online_user_list)
                msg = MessageDb(
                    from_per=None,
                    type="scan",
                    origin_content=blog.blog_title,
                    ip_detail = ip_detail,
                    content="",
                    origin_url="/sharer_blog/" + str(blog.pk) + "/",
                )
                msg.save()

            return render_to_response(
                "myblogs/blogpage.html",
                {
                    'obj': obj,
                    'comment_list': comment_list,
                    'blog_author_id': blog.blog_author.pk
                },
                context_instance=RequestContext(request)
            )

        except BlogInfoDb.DoesNotExist:
            return HttpResponse('该文章已被管理员删除！请返回<a href="/">全部文章</a>')


def add_comment(request, blog_id):
    # POST
    if request.method == "POST":
        try:

            blog = BlogInfoDb.objects.get(id=blog_id)
            dao = BlogCommentDb(
                blog=blog,
                from_user_id=request.session.get('user_id', None) ,
                head_img_url=request.session.get('head_img_url', ''),
                content=request.POST.get('comment_content', '')
            )
            dao.save()

            msg = MessageDb(
                from_per_id=request.session.get('user_id', None) ,
                type="comment",
                origin_content=blog.blog_title,
                content=dao.content,
                origin_url="/sharer_blog/" + str(blog_id) + "/#comment_div_" + str(dao.id)
            )
            msg.save()

            return HttpResponseRedirect('/sharer_blog/' + blog_id + '/#comment_div_' + str(dao.id))

        except (BlogCommentDb.DoesNotExist, MessageDb.DoesNotExist):
            return HttpResponse("评论失败！")


def to_praise(request, blog_id):
    # GET
    if request.method == "GET":
        try:
            blog = BlogInfoDb.objects.get(pk=blog_id)
            blog.praise_count += 1
            blog.scan_count -= 1
            blog.save(update_fields=("praise_count", "scan_count"))

            if request.META.has_key('HTTP_X_FORWARDED_FOR'):
                ip_message = request.META['HTTP_X_FORWARDED_FOR'] + " :" + request.META['HTTP_USER_AGENT']
            else:
                ip_message = request.META['REMOTE_ADDR'] + ":" + request.META['HTTP_USER_AGENT']
            msg = MessageDb(
                type="praise",
                origin_content=blog.blog_title,
                content=ip_message,
                origin_url="/sharer_blog/" + str(blog.id) + "/"
            )
            msg.save()

            return HttpResponseRedirect('/sharer_blog/' + blog_id + '/#article_footer')

        except BlogInfoDb.DoesNotExist:
            return HttpResponse("点赞失败！！")


def search_in_home(request):
    if request.method == "GET":
        target = request.GET.get("search_input", "")
        return search(request, target)


def search(request, target):
    if request.method == "GET":
        blog_list = BlogInfoDb.objects.filter(
            Q(blog_tags__icontains=target) | Q(blog_title__icontains=target),
            status="True"
        )

        obj = load_data(blog_list)
        obj['title'] = "搜索"

        if request.session.get('status') == 'login':
            obj['login'] = True
            obj['session'] = request.session
        return render_to_response(
            "home/index.html",
            {
                'obj': obj
            },
            context_instance=RequestContext(request)
        )
    else:
        return HttpResponse("不是POST请求！")
